package com.sunwayhorizo.health.business.patad.encounter;

import java.util.*;

import javax.ejb.Stateless;

import org.jboss.seam.*;
import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.base.*;
import com.sunwayhorizo.health.business.dto.patad.empi.*;
import com.sunwayhorizo.health.business.dto.patad.encounter.*;
import com.sunwayhorizo.health.business.dto.registries.*;
import com.sunwayhorizo.health.business.patad.encounter.query.*;
import com.sunwayhorizo.health.business.registries.person.PersonManagerLocal;
import com.sunwayhorizo.health.business.registries.place.*;
import com.sunwayhorizo.health.business.registries.place.query.*;
import com.sunwayhorizo.health.common.*;
import com.sunwayhorizo.health.hl7.common.*;
import com.sunwayhorizo.health.hl7.datatypes.*;
import com.sunwayhorizo.health.hl7.rim.*;
import com.sunwayhorizo.health.hl7.vocabulary.*;

@Name("PatientEncounterCommonManager")
@Stateless
public class PatientEncounterCommonManager extends BaseManager implements PatientEncounterCommonManagerLocal
{
    private PatientEncounterQueryLocal patientEncounterQuery = (PatientEncounterQueryLocal) Component.getInstance("PatientEncounterQuery");
    private BedManagerLocal bedManager = (BedManagerLocal) Component.getInstance("BedManager");
    private BedQueryLocal bedQueryLocal = (BedQueryLocal) Component.getInstance("BedQuery");
    private PersonManagerLocal personManager = (PersonManagerLocal) Component.getInstance("PersonManager");


    // 组装病人信息到PatientEncounterDTO
    @Override
    public PatientEncounterDTO convertByPatient(PatientEncounterDTO pateintEncouterDTO, Patient patient) throws Hl7Exception
    {
        Person person = (Person) patient.getPlayerEntity();
        PatientBaseInfoDTO baseInfo = personManager.constructorPatBaseInfo(person);
        baseInfo.setNatureId(patient.getId(RoleIICode.PATIENTID) != null ? patient.getId(RoleIICode.PATIENTID).extension().stringValue() : null);
        baseInfo.setPersonId(patient.getRoleId().toString());

        pateintEncouterDTO.setPatientBaseInfoDTO(baseInfo);
        pateintEncouterDTO.setHospitalizationNO(patient.getId(RoleIICode.ADMISSIONNO) != null ? patient.getId(RoleIICode.ADMISSIONNO).extension()
            .stringValue() : null);
        pateintEncouterDTO.setCardId(person.getId(EntityIICode.IDENTITYCARD) != null ? person.getId(EntityIICode.IDENTITYCARD).extension().stringValue()
                : null);
        pateintEncouterDTO.setCardTypeDic(person.getId(EntityIICode.IDENTITYCARD) != null ? getDictionaryFactory().getDictionaryDTOByCe(
            person.getId(EntityIICode.IDENTITYCARD).iiType()) : null);
        List<II> iis = new ArrayList<II>();
        for (RoleIICode code : RoleIICode.values())
        {
            if (code.getClazz().equals(Patient.class) && !code.equals(RoleIICode.ADMISSIONNO) && code.getConceptCode() != null)
            {

                II ii = patient.getId(code);
                if (ii != null)
                {
                    if (ii.iiState() != null && ii.iiState().stringValue() != null && ii.iiState().stringValue().equals("启用"))
                    {
                        pateintEncouterDTO.setInsuranceId(ii.extension().stringValue());
                        pateintEncouterDTO.setInsuranceTypeDic(getDictionaryFactory().getDictionaryDTOByCe(ii.iiType()));
                        return pateintEncouterDTO;
                    }
                    else
                    {
                        iis.add(ii);
                    }
                }
            }
        }
        if (!iis.isEmpty())
        {
            pateintEncouterDTO.setInsuranceId(iis.get(0).extension().stringValue());
            pateintEncouterDTO.setInsuranceTypeDic(getDictionaryFactory().getDictionaryDTOByCe(iis.get(0).iiType()));
        }
        return pateintEncouterDTO;

    }


    // 更新住院相关动作状态
    @Override
    public void updatePateintEncounter(PatientEncounter patientEncounter, CS status) throws Hl7Exception
    {

        if (patientEncounter != null && !patientEncounter.getCode().code().equals(ActCode.DISCHARGED.code()))
        {
            patientEncounter.setStatusCode(status);
            update(patientEncounter);
            log.info("PatientEncounterCommonManager-updatePateintEncounter-更新" + patientEncounter.getCode().code().stringValue() + "动作为"
                    + status.code().stringValue() + "状态");
            return;
        }
        log.info("PatientEncounterCommonManager-updatePateintEncounter-动作为空，更新失败！");
    }


    // 更新床位状态
    @Override
    public void updateBedStatus(Role bed, CS status)
    {
        if (bed != null && status != null)
        {
            bed.setStatusCode(status);
            update(bed);
            log.info("更新床位roleId" + bed.getRoleId() + "为" + status.code().stringValue() + "状态");
        }
        else
        {
            log.info("床位或状态为空！");
        }
    }


    // 查询床位
    @Override
    public Role findBedRole(PatientEncounterDTO dto) throws Hl7Exception
    {
        Role bedRole = null;
        if (!StrUtil.isEmpty(dto.getTransferDTO().getBedNo()))
        {

            bedRole = bedQueryLocal.findBedRoleByBedNoAndWorkGroupRoleId(dto.getTransferDTO().getBedNo(), dto.getTransferDTO().getFromWorkgroupCode());

        }
        else if (!StrUtil.isEmpty(dto.getInDepartment().getBedNO()))
        {

            bedRole = bedQueryLocal.findBedRoleByBedNoAndWorkGroupRoleId(dto.getInDepartment().getBedNO(), dto.getInDepartment().getWorkGroupId());

            if (bedRole == null)
            {

                BedDTO bedDTO = new BedDTO();
                bedDTO.setBedNo(dto.getInDepartment().getBedNO());
                bedDTO.setStatus(EntityStatus.UUESBED.code().stringValue());
                bedDTO.setWardId("1");

                bedDTO.setWorkGroupRoleId(dto.getInDepartment().getWorkGroupId());
                bedRole = bedManager.createBed(bedDTO);
                log.info("ReceivingManager-newReceiving-创建新床位!");
                // return getResultsDTO("床位为空,请选择正确的床位", true, false);
            }
            else
            {
                log.info("ReceivingManager-newReceiving-成功得到床位角色!");
            }
        }
        return bedRole;
    }


    public void addParticipations(Map<CS, Role> map, BaseManager baseManager) throws Hl7Exception
    {
        for (CS typeCode : map.keySet())
        {
            ActParticipation part = getActFactory().newActParticipation();
            part.setTypeCode(typeCode);
            baseManager.addParticipation(map.get(typeCode), part);
        }
    }


    @Override
    // 其他动作生成就诊号
    public II getEcounterIdForOther(PatientEncounterDTO patientEncounterDTO, CS actCode) throws Hl7Exception
    {

        // 获取就诊号
        String encounterId = null;

        if (StrUtil.isNotEmpty(patientEncounterDTO.getEncounterID()))
        {
            encounterId = patientEncounterDTO.getEncounterID();
        }
        else if (StrUtil.isNotEmpty(patientEncounterDTO.getPatientBaseInfoDTO().getNatureId()))
        {
            PatientEncounter lastInhos = patientEncounterQuery.findLastInhosActByPatientNatureId(patientEncounterDTO.getPatientBaseInfoDTO()
                .getNatureId());
            encounterId = lastInhos.getId(ActIICode.HOSPITALIZED).clinicNo().stringValue();
        }
        else
        {
            log.info("患者id为空，无法生成就诊号");
            return null;
        }
        // 就诊号
        II regIi = DataTypeUtil.getII(root, DateUtil.getNow() + getEXTEN_CODE(), "true", actCode.code().stringValue(), encounterId);

        return regIi;
    }

}
